package com.example.demo.util;

import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class TemplateEngineUtil {

    public String processTemplate(String templateContent, Map<String, Object> model) {
        MustacheFactory mf = new DefaultMustacheFactory();
        Mustache mustache = mf.compile(new StringReader(templateContent), "template");

        StringWriter writer = new StringWriter();
        mustache.execute(writer, model);
        writer.flush();

        return writer.toString();
    }

    public String readTemplateFromClasspath(String templateName) throws IOException {
        InputStream is = getClass().getClassLoader().getResourceAsStream("templates/" + templateName);
        if (is == null) {
            throw new FileNotFoundException("模板文件不存在: templates/" + templateName);
        }
        Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
        StringBuilder content = new StringBuilder();
        char[] buffer = new char[1024];
        int len;
        while ((len = reader.read(buffer)) > 0) {
            content.append(buffer, 0, len);
        }
        reader.close();
        return content.toString();
    }
}